package com.itheima.web.shiro;

import com.itheima.domain.system.Module;
import com.itheima.domain.system.User;
import com.itheima.service.system.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义reamlm
 */

public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //登陆认证    AuthenticationI:鉴定
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取到用户界面输入的邮箱密码
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String email = upToken.getUsername();
        User user = userService.findByEmail(email);
        if (user != null) {
            //第一个参数：安全数据（user对象）
            //第二个参数：密码（数据库密码）
            //第三个参数：当前调用realm域的名称（类名即可）
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
            return info;
        }
        return null;
    }

    //授权访问效验    Authorization:授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        /* 查询用户已经具有的权限并返回*/

        System.out.println("获取授权1");  //该句在缓存有效时间内只会输入一次
        //System.out.println(System.getProperty("java.io.tmpdir"));
        //1.获取当前登录的用户对象
        User user = (User) principals.getPrimaryPrincipal();
        //2.获取用户的所有权限
        List<Module> moduleList = userService.findModuleByUserId(user.getId());
        //4.构造AuthorizationInfo对象返回
        Set<String> permissions = new HashSet<>();

        for (Module module : moduleList) {
            permissions.add(module.getName());
        }
        SimpleAuthorizationInfo sai = new SimpleAuthorizationInfo();
        //将所有可操作模块的名称存入到授权对象中
        sai.addStringPermissions(permissions);
        return sai;
    }
}
